import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/global/color_config.dart';
import 'package:flutter_app/global/flutter_toast.dart';
import 'package:flutter_app/global/global_api.dart';
import 'package:flutter_app/global/login_config.dart';
import 'package:flutter_app/icon/constant_icons.dart';
import 'package:flutter_app/main/content/content.dart';
import 'package:flutter_app/main/content/model/content_model.dart';
import 'package:flutter_app/main/square/model/square_entity.dart';
import 'package:flutter_app/main/square/widget/share_article.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class SquareWidget extends StatefulWidget {
  const SquareWidget({super.key});

  @override
  SquarePageState createState() => SquarePageState();
}

class SquarePageState extends State<SquareWidget> {
  int pageIndex = 0;
  bool isRefresh = true;
  List<SquareDataDatas> listData = [];

  RefreshController controller = RefreshController(initialRefresh: false);

  void onRefresh() async {
    isRefresh = true;
    pageIndex = 0;
    getListData();
  }

  void onLoading() async {
    isRefresh = false;
    pageIndex++;
    getListData();
  }

  Future<void> getListData() async {
    String url = GlobalApi.squareListUrl(pageIndex);
    print('开始请求广场数据 $url');
    Response response = await Dio().get(url);
    var data = response.data;
    SquareEntity squareEntity = SquareEntity.fromJson(data);
    print('请求到的广场数据 $data');
    setState(() {
      if (isRefresh) {
        listData.clear();
        listData.addAll(squareEntity.data.datas);
        controller.refreshCompleted();
      } else {
        listData.addAll(squareEntity.data.datas);
        controller.loadComplete();
      }
    });
  }

  @override
  void initState() {
    super.initState();
    onRefresh();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          backgroundColor: ColorConfig.themeColor,
          elevation: 0,
          centerTitle: true,
          title: const Text(
            '广场',
            style: TextStyle(fontSize: 18, color: Colors.white),
          ),
          actions: <Widget>[
            IconButton(
              icon: const Icon(
                Icons.add,
                color: Colors.white,
              ),
              color: Colors.white,
              onPressed: () {
                if (LoginConfig.isLogin) {
                  //跳转到分享文章页
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => const ShareArticleWidget()));
                } else {
                  //跳转登录页
                  FlutterToast.showToast("您还未登录...");
                }
              },
            ),
          ]),
      body: SmartRefresher(
        controller: controller,
        enablePullDown: true,
        enablePullUp: true,
        header: const MaterialClassicHeader(),
        onRefresh: onRefresh,
        onLoading: onLoading,
        child: ListView.builder(
          itemBuilder: (c, i) => ListTile(
            onTap: () {
              Navigator.pushNamed(c, ContentWidget.RouteName,
                  arguments: ContentModel(listData[i].link));
            },
            enabled: true,
            title: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  margin: const EdgeInsets.fromLTRB(0, 10, 0, 0),
                  child: Text(
                    listData[i].shareUser,
                    style: const TextStyle(color: Colors.black54, fontSize: 12),
                  ),
                ),
                Container(
                  margin: const EdgeInsets.fromLTRB(0, 5, 0, 0),
                  child: Text(listData[i].title,
                      style:
                          const TextStyle(color: Colors.black87, fontSize: 14)),
                ),
                Container(
                  margin: const EdgeInsets.fromLTRB(0, 5, 0, 0),
                  padding: const EdgeInsets.only(bottom: 10),
                  child: Text(
                      '${listData[i].chapterName}/${listData[i].superChapterName}',
                      style:
                          const TextStyle(color: Colors.black54, fontSize: 12)),
                ),
              ],
            ),
            trailing: Column(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                Text(listData[i].niceDate,
                    style:
                        const TextStyle(fontSize: 12, color: Colors.black54)),
                const SizedBox(
                  height: 21,
                  width: 10,
                ),
                const Icon(
                  CustantIcons.squareCollectNoSelect,
                  size: 20,
                ),
              ],
            ),
          ),
          itemCount: listData.length,
        ),
      ),
    );
  }
}
